﻿using System;
using System.Collections.Generic;
using System.Text;
using WAD.DAL;
using WAD.Model;

namespace WAD.BLL
{
    public class FCOrderBLL
    {
        public static object lockObj = new object();
        /// <summary>
        /// 支付宝或微信回调，处理订单(article_id=0 只充值, >0 充值，并生成广告)
        /// </summary>
        /// <returns></returns>
        public static string Pay_CallBack(string orderId, string callbackMoney, string callbackTime, string IP, string callbackMsg, string DES_KEY)
        {
            if (string.IsNullOrEmpty(orderId)) return "订单号不能为空";
            string errMsg = "";
            bool isPush = true;         //是否需要推送
            int push_article_id = 0;    //要推送的广告ID
            lock (lockObj)
            {
                //获取订单信息
                Dictionary<string, object> model = DAOFCOrder.Get("fc_order", "orderid='" + orderId + "'");

                //校验订单是否处理过
                if (model == null) return "找不到订单";
                if (Convert.ToInt32(model["state"]) > 0)
                    return "此订单已付款";

                int platform = Convert.ToInt32(model["platform"]);        //支付方式(0余额支付,1微信支付, 2 支付宝)
                if (platform != 0 && platform != 1 && platform != 2)
                    return "支付方式错误";

                int oid = Convert.ToInt32(model["id"]);
                int user_id = Convert.ToInt32(model["user_id"]);
                int article_id = Convert.ToInt32(model["article_id"]);                  //广告ID
                decimal total_price = Convert.ToDecimal(model["total_price"]);          //订单总额
                decimal pay_price = Convert.ToDecimal(model["pay_price"]);              //在线充值金额
                string remark = platform == 1 ? "微信充值" : "支付宝充值";

                push_article_id = article_id;

                if (Convert.ToDecimal(callbackMoney) != pay_price)
                    return "充值金额不一致";

                Dictionary<string, object> uModel = DaoUser.Get("user", "id=" + model["user_id"], "ad_balance");
                decimal ad_balance = DaoUser.BalanceDncode(uModel["ad_balance"], DES_KEY);

                bool isErr = false;
                int count1 = 0, count2 = 0, count3 = 0, count4 = 0, count5 = 0;
                decimal balance = ad_balance + pay_price;   //此处是 余额 + 支付金额

                try
                {
                    //更新订单
                    count1 = DAOFCOrder.UpdateCallBack(orderId, 1, callbackMsg, callbackTime);

                    //添加支付记录
                    count2 = AddRecord(user_id, pay_price, balance, 1, oid, article_id, IP, remark);

                    //订单中有广告ID，对广告操作
                    if (article_id > 0)
                    {
                        //计算广告金额(此处是 余额 - 订单总额)
                        balance = balance - total_price;
                        if (balance >= 0)
                        {
                            //添加扣款记录
                            count3 = AddRecord(user_id, (total_price * -1), balance, 2, oid, article_id, IP, "广告扣款,ID:" + article_id.ToString());
                            //更新广告状态
                            count5 = DAOFCArticle.SetShared(article_id, user_id, 1);
                        }
                    }

                    //更新账户余额
                    if (balance < 0) balance = 0;
                    count4 = DaoUser.UpdateBalance(user_id, balance, 1);
                }
                catch (Exception ex) { isErr = true; errMsg = ex.Message; }

                #region 抛异常，回滚操作
                if (isErr)
                {
                    isPush = false;
                    if (count1 > 0)
                    {
                        DAOFCOrder.UpdateCallBack(orderId, 0, "", "");
                    }
                    if (count4 > 0)
                    {
                        if (count3 > 0)
                            balance = balance + total_price;                    //有扣费记录，则回滚扣除的金额
                        DaoUser.UpdateBalance(user_id, balance - pay_price, 1); //减去充值的金额
                    }
                    if (count5 > 0)
                        DAOFCArticle.SetShared(article_id, user_id, 0);         //回滚文章状态
                }
                #endregion
            }
            //推送通知(article_id >0 才推送)
            if (isPush && push_article_id > 0)
            {
                Dictionary<string, object> article = DAOFCArticle.GetArea(push_article_id);
                if (article != null)
                {
                    //添加推送队列 0613
                    DAOPushLog.Add(push_article_id, article["op_area1"], article["op_area2"], article["op_area3"]);

                    //PushBLL.Shared_Betch(push_article_id, DAOFCSetting.GetListPush(article["op_area1"], article["op_area2"], article["op_area3"]));
                    ////测试账号推送
                    //PushBLL.PushOtherUser(push_article_id, article["op_area1"], article["op_area2"], article["op_area3"]);
                }
            }
            return errMsg;
        }


        public static string Sys_CallBack(string orderId, string IP, string DES_KEY)
        {
            if (string.IsNullOrEmpty(orderId)) return "订单号不能为空";
            string errMsg = "";
            bool isPush = true;         //是否需要推送
            int push_article_id = 0;    //要推送的广告ID
            int number=0;
            lock (lockObj)
            {
                //获取订单信息
                Dictionary<string, object> model = DAOFCOrder.Get("fc_order", "orderid='" + orderId + "'");

                //校验订单是否处理过
                if (model == null) return "找不到订单";
                if (Convert.ToInt32(model["state"]) > 0)
                    return "此订单已付款";

                int platform = Convert.ToInt32(model["platform"]);        //支付方式(0余额支付,1微信支付, 2 支付宝)
                if (platform != 0)
                    return "支付方式错误";

                int oid = Convert.ToInt32(model["id"]);
                int user_id = Convert.ToInt32(model["user_id"]);                
                int article_id = Convert.ToInt32(model["article_id"]);                  //广告ID
                decimal total_price = Convert.ToDecimal(model["total_price"]);          //订单总额
                decimal pay_price = Convert.ToDecimal(model["pay_price"]);              //在线充值金额
                number = Convert.ToInt32(model["number"]);                              //广告数量
                push_article_id = article_id;

                Dictionary<string, object> uModel = DaoUser.Get("user", "id=" + model["user_id"], "ad_balance");
                decimal ad_balance = DaoUser.BalanceDncode(uModel["ad_balance"], DES_KEY);

                bool isErr = false;
                int count1 = 0, count3 = 0, count4 = 0, count5 = 0;
                decimal balance = ad_balance;   //此处是 余额

                try
                {
                    //更新订单
                    count1 = DAOFCOrder.UpdateCallBack(orderId, 1, string.Format("余额支付,金额:{0},原余额:{1}", total_price, balance), DateTime.Now.ToString());

                    //计算广告金额(此处是 余额 - 订单总额)
                    balance = balance - total_price;
                    //添加扣款记录
                    count3 = AddRecord(user_id, (total_price * -1), balance, 2, oid, article_id, IP, "广告扣款,ID:" + article_id.ToString());
                    //更新广告状态
                    count5 = DAOFCArticle.SetShared(article_id, user_id, 1);

                    //更新账户余额
                    if (balance < 0) balance = 0;
                    count4 = DaoUser.UpdateBalance(user_id, balance, 1);
                }
                catch (Exception ex) { isErr = true; errMsg = ex.Message; }

                #region 抛异常，回滚操作
                if (isErr)
                {
                    isPush = false;
                    if (count1 > 0)
                        DAOFCOrder.UpdateCallBack(orderId, 0, "", "");

                    if (count4 > 0)
                    {
                        balance = balance + total_price;                    //有扣费记录，则回滚扣除的金额
                        DaoUser.UpdateBalance(user_id, balance, 1);
                    }
                    if (count5 > 0)
                        DAOFCArticle.SetShared(article_id, user_id, 0);         //回滚文章状态
                }
                #endregion
            }
            //推送通知(article_id >0 才推送)
            if (isPush && push_article_id > 0)
            {
                //生成红包       
                try
                {
                    DAOFCSharedMoney.Add_HongBao(push_article_id, number);
                }
                catch { }
                
                Dictionary<string, object> article = DAOFCArticle.GetArea(push_article_id);
                if (article != null)
                {
                    //添加推送队列 0613
                    DAOPushLog.Add(push_article_id, article["op_area1"], article["op_area2"], article["op_area3"]);

                    //PushBLL.Shared_Betch(push_article_id, DAOFCSetting.GetListPush(article["op_area1"], article["op_area2"], article["op_area3"]));
                    ////测试账号推送
                    //PushBLL.PushOtherUser(push_article_id, article["op_area1"], article["op_area2"], article["op_area3"]);
                }
            }
            return errMsg;
        }
        /// <summary>
        /// 微信专用
        /// </summary>
        /// <param name="orderId"></param>
        /// <param name="IP"></param>
        /// <param name="DES_KEY"></param>
        /// <returns></returns>
        public static string Sys_CallBack2(string orderId, string IP, string DES_KEY)
        {
            if (string.IsNullOrEmpty(orderId)) return "订单号不能为空";
            string errMsg = "";
            bool isPush = true;         //是否需要推送
            int push_article_id = 0;    //要推送的广告ID
            int number = 0;
            lock (lockObj)
            {
                //获取订单信息
                Dictionary<string, object> model = DAOFCOrder.Get("fc_order", "orderid='" + orderId + "'");

                //校验订单是否处理过
                if (model == null) return "找不到订单";
                if (Convert.ToInt32(model["state"]) > 0)
                    return "此订单已付款";

                int platform = Convert.ToInt32(model["platform"]);        //支付方式(0余额支付,1微信支付, 2 支付宝)
                if (platform != 0)
                    return "支付方式错误";

                int oid = Convert.ToInt32(model["id"]);
                int user_id = Convert.ToInt32(model["user_id"]);
                int article_id = Convert.ToInt32(model["article_id"]);                  //广告ID
                decimal total_price = Convert.ToDecimal(model["total_price"]);          //订单总额
                decimal pay_price = Convert.ToDecimal(model["pay_price"]);              //在线充值金额
                number = Convert.ToInt32(model["number"]);                              //广告数量
                push_article_id = article_id;

                Dictionary<string, object> uModel = DaoUser.Get("user", "id=" + model["user_id"], "ad_balance");
                decimal ad_balance = DaoUser.BalanceDncode(uModel["ad_balance"], DES_KEY);

                bool isErr = false;
                int count1 = 0, count3 = 0, count4 = 0, count5 = 0;
                decimal balance = ad_balance;   //此处是 余额

                try
                {
                    //更新订单
                    count1 = DAOFCOrder.UpdateCallBack(orderId, 1, string.Format("余额支付,金额:{0},原余额:{1}", total_price, balance), DateTime.Now.ToString());

                    //计算广告金额(此处是 余额 - 订单总额)
                    balance = balance - total_price;
                    //添加扣款记录
                    count3 = AddRecord(user_id, (total_price * -1), balance, 2, oid, article_id, IP, "广告扣款,ID:" + article_id.ToString());
                    //更新广告状态
                    count5 = DAOFCArticle.SetShared(article_id, user_id, 1);

                    //更新账户余额
                    if (balance < 0) balance = 0;
                    count4 = DaoUser.UpdateBalance(user_id, balance, 1);
                }
                catch (Exception ex) { isErr = true; errMsg = ex.Message; }

                #region 抛异常，回滚操作
                if (isErr)
                {
                    isPush = false;
                    if (count1 > 0)
                        DAOFCOrder.UpdateCallBack(orderId, 0, "", "");

                    if (count4 > 0)
                    {
                        balance = balance + total_price;                    //有扣费记录，则回滚扣除的金额
                        DaoUser.UpdateBalance(user_id, balance, 1);
                    }
                    if (count5 > 0)
                        DAOFCArticle.SetShared(article_id, user_id, 0);         //回滚文章状态
                }
                #endregion
            }
            //推送通知(article_id >0 才推送)
            if (isPush && push_article_id > 0)
            {
                //生成红包       
                try
                {
                    DAOFCSharedMoney.Add_HongBao2(push_article_id, number);
                }
                catch { }

                Dictionary<string, object> article = DAOFCArticle.GetArea(push_article_id);
                if (article != null)
                {
                    //添加推送队列 0613
                    DAOPushLog.Add(push_article_id, article["op_area1"], article["op_area2"], article["op_area3"]);

                    //PushBLL.Shared_Betch(push_article_id, DAOFCSetting.GetListPush(article["op_area1"], article["op_area2"], article["op_area3"]));
                    ////测试账号推送
                    //PushBLL.PushOtherUser(push_article_id, article["op_area1"], article["op_area2"], article["op_area3"]);
                }
            }
            return errMsg;
        }
        static int AddRecord(int user_id, decimal pay_price, decimal ad_balance, int direction, int orderId, int article_id, string IP, string remark)
        {
            MFCRecord rModel = new MFCRecord();
            rModel.user_id = user_id;
            rModel.amount = pay_price;
            rModel.balance = ad_balance;
            rModel.direction = direction;
            rModel.orderid = orderId;
            rModel.article_id = article_id;
            rModel.ip = IP;
            rModel.remark = remark;
            rModel.date = DateTime.Now;
            return DAOFCRecord.Add(rModel);
        }
        public static string CreateId(int user_id)
        {
            Random rand = new Random();
            //格式：3位毫秒+时间戳+3位随机数 如：5661452508460869
            return DateTime.Now.ToString("fff") + GetTimeStamp() + rand.Next(100, 999).ToString();
        }
        static string GetTimeStamp()
        {
            TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);
            return Convert.ToInt64(ts.TotalSeconds).ToString();
        }
    }
}